package com.hundsun.cprs.yyt.web.action.trade;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.domain.query.TradeRollbackFlowQuery;
import com.hundsun.cprs.yyt.service.trade.enums.EnumEntustRollbackStatus;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustRollbackService;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustService;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.cprs.yyt.web.vo.JsonModel;
import com.hundsun.eclp.biz.domain.user.UserAgent;

@Controller
@RequestMapping("/trade/entrust/rollback")
public class TradeEntrustRollbackAction extends BaseAction {
    
    @Autowired
    private TradeEntrustService tradeEntrustService;
    @Autowired
    private TradeEntrustRollbackService rollbackService;
    
    @RequestMapping("/list")
    public void list(@ModelAttribute("query") TradeRollbackFlowQuery query,ModelMap model){
        rollbackService.selectByPage(query);
        model.put("rollbackStatusMap", EnumEntustRollbackStatus.toMap());
    }
    
    @RequestMapping("/apply")
    public String applyRollback(Long entrustId, ModelMap model, UserAgent userAgent) throws Exception {
        TradeEntrust entrust = tradeEntrustService.getTradeEntrustById(entrustId);
        if (entrust == null) {
            return error(model, "委托单不存在");
        }
        try {
            rollbackService.applyRollbackEntrust(entrust);
        } catch (Exception e) {
            log.error("申请撤回失败:",e);
            return error(model,e.getMessage());
        }
        
        return "redirect:/trade/entrust/rollback/list.htm?entrustNo=" + entrust.getEntrustNo();
    }
    
    @RequestMapping("/applyBatch")
    @ResponseBody
    public JsonModel applyRollbackBatch(String entrustIds,ModelMap model,UserAgent userAgent){
        String[] ids = entrustIds.split(",");
        int success = 0;
        for(String item : ids){
            try {
                TradeEntrust entrust = tradeEntrustService.getTradeEntrustById(Long.valueOf(item));
                rollbackService.applyRollbackEntrust(entrust);
                success++;
            } catch (Exception e) {
                log.error("申请撤回失败:",e);
            }
        }
        return new JsonModel(JsonModel.RESULD_CODE_SUCCESS, "申请撤回成功数:" + success);
    }
}
